<?php
namespace Admin\Model;
use Think\Model;
class OrderModel extends Model 
{
	protected $insertFields = array('member_id','pay_status','pay_time','total_price','shr_name','shr_tel','shr_province','shr_city','shr_area','shr_address','post_status','post_number','inv_payee','inv_content');
	protected $updateFields = array('id','member_id','pay_status','pay_time','total_price','shr_name','shr_tel','shr_province','shr_city','shr_area','shr_address','post_status','post_number');
	protected $_validate = array(
//		array('member_id', 'require', '会员Id不能为空！', 1, 'regex', 3),
//		array('member_id', 'number', '会员Id必须是一个整数！', 1, 'regex', 3),
//		array('pay_status', '否,是', "支付状态的值只能是在 '否,是' 中的一个值！", 2, 'in', 3),
//		array('pay_time', 'number', '支付时间必须是一个整数！', 2, 'regex', 3),
//		array('total_price', 'require', '订单总价不能为空！', 1, 'regex', 3),
//		array('total_price', 'currency', '订单总价必须是货币格式！', 1, 'regex', 3),
//		array('shr_name', 'require', '收货人姓名不能为空！', 1, 'regex', 3),
//		array('shr_name', '1,30', '收货人姓名的值最长不能超过 30 个字符！', 1, 'length', 3),
//		array('shr_tel', 'require', '收货人地址不能为空！', 1, 'regex', 3),
//		array('shr_tel', '1,30', '收货人地址的值最长不能超过 30 个字符！', 1, 'length', 3),
//		array('shr_province', 'require', '收货人省不能为空！', 1, 'regex', 3),
//		array('shr_province', '1,30', '收货人省的值最长不能超过 30 个字符！', 1, 'length', 3),
//		array('shr_city', 'require', '收货人城市不能为空！', 1, 'regex', 3),
//		array('shr_city', '1,30', '收货人城市的值最长不能超过 30 个字符！', 1, 'length', 3),
//		array('shr_area', 'require', '收货人地区不能为空！', 1, 'regex', 3),
//		array('shr_area', '1,30', '收货人地区的值最长不能超过 30 个字符！', 1, 'length', 3),
//		array('shr_address', 'require', '收货人详细地址不能为空！', 1, 'regex', 3),
//		array('shr_address', '1,30', '收货人详细地址的值最长不能超过 30 个字符！', 1, 'length', 3),
//		array('post_status', 'number', '发货状态,0:未发货,1:已发货2:已收到货必须是一个整数！', 2, 'regex', 3),
//		array('post_number', '1,30', '快递号的值最长不能超过 30 个字符！', 2, 'length', 3),
	);

    static public function get_order_sn(){
        mt_srand((double) microtime() * 1000000);
        return date('Ymd').str_pad(mt_rand(1,99999), 5, '0',STR_PAD_LEFT);
    }

    public function search($pageSize = 20)
    {
        /**************************************** 搜索 ****************************************/
        $memberId = session('m_id');
        $where['member_id'] = array('eq', $memberId);
        $noPayCount = $this->where(array(
            'member_id' => array('eq', $memberId),
            'pay_status' => array('eq', '否'),
        ))->count();
        /************************************* 翻页 ****************************************/
        $count = $this->alias('a')->where($where)->count();
        $page = new \Think\Page($count, $pageSize);
        // 配置翻页的样式
        $page->setConfig('prev', '上一页');
        $page->setConfig('next', '下一页');
        $data['page'] = $page->show();
        /************************************** 取数据 ******************************************/
        $data['data'] = $this->alias('a')
            ->field('a.id,a.shr_name,a.order_sn,a.total_price,a.addtime,a.pay_status,a.post_status,a.order_status,GROUP_CONCAT(DISTINCT c.sm_logo) logo')
            ->join('LEFT JOIN __ORDER_GOODS__ b ON a.id=b.order_id 
		        LEFT JOIN __GOODS__ c ON b.goods_id=c.id')
            ->where($where)
            ->group('a.id')
            ->limit($page->firstRow.','.$page->listRows)
            ->select();
        $data['noPayCount'] = $noPayCount;
        return $data;
    }


    /***** 添加前 ********/
	protected function _before_insert(&$data, &$option)
    {
	    $memberId = session('m_id');
        if (!$memberId){
            $this->error = '必须先登录!';
            return FALSE;
        }

        //购物车是否有商品
        $cartModel = D('Cart');
        $option['goods'] = $goods = $cartModel->cartList();
        if (!$goods){
            $this->error='购物车没有商品,无法下单!';
            return FASLE;
        }
        //读库存前加锁,
        $this->fp = fopen('./order.lock');
        flock($this->fp,LOCK_EX);

        //循环购物车中的商品检查库存量并且计算商品总价
        $gnModel = D('goods_number');
        $total_price = 0;
        foreach($goods as $k => $v){
            //检查库存量
            $gnNumber = $gnModel->field('goods_number')->where(array(
                'goods_id' => array('eq',$v['goods_id']),
                'goods_attr_id' => array('eq',$v['goods_attr_id']),
            ))->find();
            if($gnNumber['goods_number'] < $v['goods_number']){
                $this->error = '下单失败,原因:商品<strong>'.$v['goods_name'].'</strong>库存量不足!';
                return false;
            }
            //统计总价
            $total_price += $v['price'] * $v['goods_number'];
        }

        //把其他信息补到订单中
        $data['order_sn'] = self::get_order_sn();
        $data['total_price'] = $total_price;
        $data['member_id'] = $memberId;
        $data['addtime'] = time();

        $address_id = I('post.address_id',0);
        if ($address_id){
            $addressModel = D("Admin/UserAddress");
            $addressData = $addressModel->relation(true)->find($address_id);
            $data['shr_name'] = $addressData['consignee'];
            $data['shr_tel'] = $addressData['mobile'];
            $data['shr_province'] = $addressData['province']['region_name'];
            $data['shr_city'] = $addressData['city']['region_name'];
            $data['shr_area'] = $addressData['district']['region_name'];
            $data['shr_address'] = $addressData['address'];
        } else{
            $this->error='请选择收货地址!';
            return false;
        }

        //送货方式
        $shipping_id = I('post.shipping_id', 0);
        $config_option = I('post.config_option');
        if($shipping_id){
            $shippingModel = D('Admin/Shipping');
            $shippingData = $shippingModel->find($shipping_id);
            $data['shipping_id'] = $shippingData['shipping_id'];
            $data['shipping_name'] = $shippingData['shipping_name'].' '.$config_option[$shipping_id];
        } else {
            $this->error = '请选择送货方式！';
            return FALSE;
        }

        //发票信息
        if($data['inv_payee']=='personal'){
            $data['inv_payee'] = '个人';
        }elseif($data['inv_payee']=='company'){
            $data['inv_payee'] = '单位：' . I('post.company_name');
        }

        // 为了确定三张表的操作都能成功：定单基本信息表，定单商品表，库存量表
        $this->startTrans();
    }
	// 修改前
	protected function _before_update(&$data, $option)
	{

    }
	// 删除前
	protected function _before_delete($option)
	{
		if(is_array($option['where']['id']))
		{
			$this->error = '不支持批量删除';
			return FALSE;
		}
	}
	/************************************ 其他方法 ********************************************/

    protected function _after_insert($data, $option)
    {
        // 从$option中取出购物车中的商品并循环插入到定单商品表中并且减少库存
        $ogModel = D('order_goods');
        $gnModel = D('goods_number');
        foreach ($option['goods'] as $k => $v)
        {
            $ret = $ogModel->add(array(
                'order_id' => $data['id'],
                'goods_id' => $v['goods_id'],
                'goods_attr_id' => $v['goods_attr_id'],
                'goods_number' => $v['goods_number'],
                'price' => $v['price'],
            ));
            if(!$ret)
            {
                $this->rollback();
                return FALSE;
            }
            // 减库存
            $ret = $gnModel->where(array(
                'goods_id' => array('eq', $v['goods_id']),
                'goods_attr_id' => array('eq', $v['goods_attr_id']),
            ))->setDec('goods_number', $v['goods_number']);
            if(FALSE === $ret)
            {
                $this->rollback();
                return FALSE;
            }
        }

        // 所有操作都成功提交事务
        $this->commit();

        // 释放锁
        flock($this->fp, LOCK_UN);
        fclose($this->fp);

        // 清空购物车
        $cartModel = D('Cart');
        $cartModel->clear();
    }

    /**
     * 取出一个订单详细信息
     * @param $orderId
     * @return array
     */
    public function getDetail($orderId){
        $goodsModel = D('Admin/Goods');
        $goodsAttrModel = D('Admin/GoodsAttr');
        $orderGoodsModel = D('Admin/OrderGoods');
        $orderData = $this->find($orderId);
        $orderData['goods_list'] = $orderGoodsModel->where(array('order_id'=>$orderId))->select();
        foreach($orderData['goods_list'] as $k => &$v){
            $goodsData = $goodsModel->field("goods_name,sm_logo")->find($v['goods_id']);
            $v['goods_name'] = $goodsData['goods_name'];
            $v['sm_logo'] = $goodsData['sm_logo'];
            if($v['goods_attr_id']){
                $v['gaData'] = $goodsAttrModel->alias('a')
                    ->field('a.attr_value, b.attr_name')
                    ->join('LEFT JOIN __ATTRIBUTE__ b ON a.attr_id = b.id')
                    ->where(array(
                        'a.id' => array('IN', $v['goods_attr_id'])
                    ) )->select();
            }
        }
        return $orderData;
    }

}